package com.voicechat.firstmet.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.adapter.PhotoAlbumGroupAdapter;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.PhotoAlbumPictureBean;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.net.service.PersonDataService;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;
import com.voicechat.firstmet.view.grouprecyclerview.GroupedGridLayoutManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: PhotoAlbumActivity
 * @Description: 相册activity
 * @Author: ljp
 * @CreateDate: 2018/10/10 11:23
 * @Version: 1.0
 */
public class PhotoAlbumActivity extends BaseActivity {
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.recycler_photo_album)
    RecyclerView recyclerPhotoAlbum;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.tv_uploading)
    TextView tvUploading;
    @BindView(R.id.linear_layout)
    LinearLayout linearLayout;
    @BindView(R.id.image_delete)
    ImageView imageDelete;
    private String anchorId;
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String token;
    private String id;
    private String deviceInfo;
    private String TAG = "PhotoAlbumActivity";
    private int page;
    private List<PhotoAlbumPictureBean.PageBean.SetBean> setBeanList;
    private PhotoAlbumGroupAdapter photoAlbumGroupAdapter;
    private OnClickDelete onClickDelete;

    public void setOnClickDelete(OnClickDelete onClickDelete) {
        this.onClickDelete = onClickDelete;
    }

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_photo_album;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        anchorId = getIntent().getStringExtra("anchorId");//对方的id
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        id = mySeleInfo.getId();
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        initView();
        setPhotos();
    }

    /**
     * @return
     * @method
     * @description 数据控件实例化
     * @date: 2018/11/29 18:55
     * @author: ljp
     */
    private void initView() {
        if (anchorId.equals(id)) {
            tvUploading.setVisibility(View.VISIBLE);
            imageDelete.setVisibility(View.VISIBLE);
        }
        page = 1;
        setBeanList = new ArrayList<>();
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                setPhotos();
                smartRefresh.finishRefresh(10000);
            }
        });
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                setPhotos();
                smartRefresh.finishLoadMore(10000);
            }
        });
        //设置 Header 为 贝塞尔雷达 样式
        smartRefresh.setRefreshHeader(new ClassicsHeader(context));
        //设置 Header 为 贝塞尔雷达 样式
        smartRefresh.setRefreshFooter(new ClassicsFooter(context));
        photoAlbumGroupAdapter = new PhotoAlbumGroupAdapter(this, setBeanList);
        //直接使用GroupedGridLayoutManager实现子项的Grid效果
        GroupedGridLayoutManager gridLayoutManager = new GroupedGridLayoutManager(this, 3, photoAlbumGroupAdapter);
        recyclerPhotoAlbum.setLayoutManager(gridLayoutManager);
        recyclerPhotoAlbum.setAdapter(photoAlbumGroupAdapter);
        photoAlbumGroupAdapter.setOnClick(new PhotoAlbumGroupAdapter.OnClick() {
            @Override
            public void onSetPictureClick(View view, List<PhotoAlbumPictureBean.PageBean.SetBean.ValieBean> valie, int position) {
                ArrayList<String> stringArrayList = new ArrayList<>();
                for (int i = 0; i < valie.size(); i++) {
                    stringArrayList.add(valie.get(i).getAlbumUrl());
                }
                Intent intent = new Intent(context, PictureViewerActivity.class);
                Bundle bundle = new Bundle();
                bundle.putStringArrayList("tlist", stringArrayList);
                intent.putExtra("position", position);
                intent.putExtra("list", bundle);
                context.startActivity(intent);
            }
        });
        tvUploading.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消删除
                if (isSureDelete == 1) {
                    isSureDelete = 0;
                    imageDelete.setImageResource(R.mipmap.photo_delete);
                    //onClickDelete.setDelete(isSureDelete);
                    for (int i = 0; i < setBeanList.size(); i++) {
                        for (int j = 0; j < setBeanList.get(i).getValie().size(); j++) {
                            setBeanList.get(i).getValie().get(j).setSelectDelete(0);
                        }
                    }
                    photoAlbumGroupAdapter.notifyDataChanged();
                    tvUploading.setText("上传");
                } else {
                    startActivity(new Intent(activity, UploadingActivity.class));
                    finish();
                }
            }
        });
    }

    private void setPhotos() {
        PersonDataService.photosAlbum(token, deviceInfo, anchorId, page + "").subscribe(photoAlbumPictureBean -> {
            //Log.i(TAG, "setPhotos: -----getValie-----"+photoAlbumPictureBean.getPage().getSet().get(0).getValie().size());
            if (photoAlbumPictureBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                int i = photoAlbumPictureBean.getPage().getCount() / photoAlbumPictureBean.getPage().getPageSize() +
                        (photoAlbumPictureBean.getPage().getCount() % photoAlbumPictureBean.getPage().getPageSize() == 0 ? 0 : 1);
                //int i = postBean.getPage().getCount() % postBean.getPage().getPageSize();
                //Log.i(TAG, "setHttpData: ----i+++++"+i);
                if (i != 0 && page > i) {//判断是否是最后一页
                    smartRefresh.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据 1.0.4
                } else {
                    if (page == 1) {
                        setBeanList.clear();
                        smartRefresh.finishRefresh();
                        isSureDelete = 0;
                        imageDelete.setImageResource(R.mipmap.photo_delete);
                        tvUploading.setText("上传");
                    }
                    if (photoAlbumPictureBean.getPage().getSet() != null) {
                        if (isSureDelete == 1) {
                            for (int n = 0; n < photoAlbumPictureBean.getPage().getSet().size(); n++) {
                                for (int j = 0; j < photoAlbumPictureBean.getPage().getSet().size(); j++) {
                                    photoAlbumPictureBean.getPage().getSet().get(n).getValie().get(j).setSelectDelete(-1);
                                }
                            }
                        }
                        setBeanList.addAll(photoAlbumPictureBean.getPage().getSet());
                        photoAlbumGroupAdapter.notifyDataSetChanged();
                        smartRefresh.setVisibility(View.VISIBLE);
                    } else {
                        linearLayout.setVisibility(View.VISIBLE);
                    }
                    smartRefresh.finishLoadMore();
                }
            } else if (photoAlbumPictureBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(photoAlbumPictureBean.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "setPhotos: -----" + throwable.toString());

        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @OnClick({R.id.linear_back, R.id.image_delete})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.linear_back:
                finish();
                break;
            case R.id.image_delete:
                if (isSureDelete == -1 || isSureDelete == 0) {
                    tvUploading.setText("取消");
                    imageDelete.setImageResource(R.mipmap.photo_sure);
                    //onClickDelete.setDelete(isSureDelete);
                    isSureDelete = 1;
                    for (int i = 0; i < setBeanList.size(); i++) {
                        for (int j = 0; j < setBeanList.get(i).getValie().size(); j++) {//是删除还是选定 -1选定  1删除 0取消选定
                            setBeanList.get(i).getValie().get(j).setSelectDelete(-1);
                        }
                    }
                    photoAlbumGroupAdapter.notifyDataChanged();
                } else {
                    Log.i(TAG, "onClick: ----photoAlbumGroupAdapter------" + photoAlbumGroupAdapter.getSb().size());
                   if(photoAlbumGroupAdapter.getSb().size() != 0) {
                       StringBuffer stringBuffer = new StringBuffer();
                       for (int i = 0; i < photoAlbumGroupAdapter.getSb().size(); i++) {
                           stringBuffer.append(photoAlbumGroupAdapter.getSb().get(i) + ",");
                       }
                       stringBuffer.deleteCharAt(stringBuffer.length() - 1);
                       showCacheDialog(stringBuffer.toString());
                   } else {
                       toast_MakeText("请选择删除照片");
                   }
                }
                break;
        }
    }

    /**
     * @return
     * @method
     * @description 删除照片
     * @date: 2018/11/1 19:37
     * @author: ljp
     */
    private void showCacheDialog(String string) {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(context);
        //normalDialog.setTitle("我是一个普通Dialog");
        normalDialog.setMessage("确认删除?");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        dialog.dismiss();
                        deleteAlbum(string);
                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        dialog.dismiss();
                    }
                });
        // 显示
        normalDialog.show();
    }

    /**
     * @return
     * @method
     * @description 删除照片
     * @date: 2018/12/21 16:01
     * @author: ljp
     */
    private void deleteAlbum(String string) {
        MeInfoService.deletePhoto(token, deviceInfo, string).subscribe(result -> {
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                photoAlbumGroupAdapter.getSb().clear();
                smartRefresh.autoRefresh();
                //smartRefresh.finishRefresh(10000);
                toast_MakeText("删除成功");
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(result.getMsg());
            }
        }, throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
        });

    }

    private int isSureDelete = -1;//是删除还是选定 -1选定  1删除 0取消选定

    public interface OnClickDelete {
        void setDelete(int isSureDelete);
    }

}
